<?php
namespace Home\Controller;

use Think\Controller;
use Common\Org\Wxapi\WxBaseInterfaceUtil;
use Common\Org\Wxapi\WxConf;

class BaseController extends Controller {
	public $settingCity;
    public $settingProvince;
    
    public function __construct() {
    	parent::__construct();
    	
    	if (!IS_AJAX) {
    		if(!C('IS_LOCATION')){
    			if (isset($_COOKIE ['openid']) || $_GET ['openid']) {
    				$openid = $_COOKIE ['openid']?$_COOKIE ['openid']:$_GET ['openid'];
    				if ($openid) {
    					$wxVisitorModel = M ('wx_visitor');
    					
    					$visitor = $wxVisitorModel->where(array('openid' => $openid))->find();
    					$_SESSION['mdd_wx_user'] = serialize($visitor);
    				}
    			}
    			
    			if(!isset($_SESSION['mdd_wx_user'])) {
    				$rurl = urlencode($_SERVER["REQUEST_URI"]);
    				$wxBaseInterface_util = new WxBaseInterfaceUtil();
    				$url = $wxBaseInterface_util->createOauthUrlForCode(urlencode(WxConf::JS_API_CALL_URL."?rurl=".$rurl));
    			
    				header("Location: $url");
    				exit();
    			}
    					
    			//调用分享的JS需要
    			$signPackage = getSignPackage();
    					
    			$this->assign("appId", $signPackage["appId"]);
    			$this->assign("timestamp", $signPackage["timestamp"]);
    			$this->assign("noncestr", $signPackage["nonceStr"]);
    			$this->assign("signature", $signPackage["signature"]);
    			$this->assign("url", $signPackage["url"]);
    		}
    		
    		$openid = $this->getOpenid();
    		
    		$expires_time = time() + 7 * 24 * 3600;
    		setcookie('openid', $openid, $expires_time, '/');
    		
    		$cityConfig = S('user_select_city_'.$openid);
    		if ($cityConfig) {
    			$this->settingCity = $cityConfig ['select_city'];
    			$this->settingProvince = $cityConfig ['select_province'];
    			
    			//保存用户选择的城市
    			setcookie('select_province', $this->settingProvince, $expires_time, '/');
    			setcookie('select_city', $this->settingCity, $expires_time, '/');
    			
    			$this->assign('currentCity', $this->settingCity);
    			$this->assign('select_province', $this->settingProvince);
    			$this->assign('select_city', $this->settingCity);
    		}
    		
    		if (C('JS_DEBUG')) {
    			$this->assign('JSDEBUG', '?t='.time());
    		}
    		$this->assign('select', CONTROLLER_NAME);
    	}
    	
    	$setting = getGlobleConfig();
    	$this->assign('service_hotline', $setting ['service_hotline']);
    	$this->assign('format_service_hotline', format_phone($setting ['service_hotline']));
    }
    
    public function nodata($title, $content) {
    	$this->assign('title', $title);
    	$this->assign('content', $content);
    	
    	$this->display('Public/nodata');
    	exit;
    }
    
    public function notfind($redirect = false) {
    	if (!$redirect) {
    		$redirect = U('ServiceItem/index');
    	}
    	$this->assign('redirect', $redirect);
    	$this->display('Public/404');
    	exit;
    }
    
    /**
     * 获取用户openid
     * @return Ambigous <string, mixed>
     */
    public function getOpenId() {
    	$wxUser = unserialize($_SESSION['mdd_wx_user']);
		$open_id = $wxUser['openid'];
		if(C('IS_LOCATION')){
			$open_id = 'oLJ_ashGTT2VwutuOqUJpuC9c2B4';
		}
		return $open_id;
    }
    
    public function getSessionUser() {
    	$openId = $this->getOpenId();
    	if (!isset($_SESSION ['mdd_user'])) {
    		$user = D('User')->where(array('open_id' => $openId))->find();
    		if (!$user || ($user && !$user ['mobile'])) {
    			return false;
    		} else {
    			$_SESSION ['mdd_user'] = serialize($user);
    		}
    	} else {
    		$user = unserialize($_SESSION ['mdd_user']);
    	}
    	
    	return $user;
    }
    
    /**
     * 格式化地址与点的距离
     * 
     * @param array $list
     * @return boolean|Ambigous <:, boolean, unknown>
     */
    public function formatAddressDistance($list) {
    	if (!$list) {
    		return false;
    	}
    	
		$lat = I('get.lat');
		$lng = I('get.lng');

		$queryDistance = false;
		if ($lat && $lng) {
			$queryDistance = true;
			$start = array(
				'latitude' => $lat,
				'longitude' => $lng
			);
		}

		foreach ( $list as $key => &$value ) {
			if ($value ['professional_score'] || $value ['punctuality_score'] || $value ['communication_score']) {
				$value ['start'] = ceil(($value ['professional_score'] + $value ['punctuality_score'] + $value ['communication_score'])/3/$value ['comment_total']);
			} else {
				$value ['start'] = 0;
			}

			if ($queryDistance) {
				$end = array(
					'latitude' => $value ['latitude'],
					'longitude' => $value ['longitude']
				);

				$d = getDistance($start, $end);
				$list [$key] ['mathDis'] = $d;
				if ($d < 1) {
					$list[$key] ['distance'] = round($d * 1000).'m';
				} else {
					$list[$key] ['distance'] = round($d, 1).'km';
				}
			}
		}
		
		if ($queryDistance) {
			$list = multi_array_sort($list, 'mathDis');
			
		} else {
			$list = multi_array_sort($list, 'start', SORT_DESC);
		}
		
		return $list;
    }
}